package com.woniu.darryringmall.front.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.darryringmall.front.entity.Category;
import com.woniu.darryringmall.front.mapper.CategoryMapper;
import com.woniu.darryringmall.front.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getByPid() {
        List<Category> menus = categoryMapper.getByPid(0);
        getChild(menus);
        return menus;
    }

    @Override
    public Category getByName(String name) {
        return categoryMapper.getByName(name);
    }

    @Transactional
    @Override
    public void delAll(int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("pid", id);
        List<Category> categorys = categoryMapper.selectByMap(map);
        if (categorys != null) {
            for (Category category : categorys) {
                delAll(category.getId());
            }
        }
        categoryMapper.deleteById(id);
    }

    private void getChild(List<Category> parent) {
        for (Category category : parent) {
            List<Category> child = categoryMapper.getByPid(category.getId());
            if (child != null) {
                getChild(child);
            }
            category.setChild(child);
        }
    }

    public List<Category> getList(String type){
        return categoryMapper.getList(type);
    }

}
